<template>
  <basic-container>
    <div class="sku-table">
      <el-row :gutter="10" v-if="skuData.length > 0">
        <el-col :span="3">批量设置</el-col>
        <!--
        <el-col :span="3">
          <el-input
            size="mini"
            placeholder="sku编码"
            clearable
            v-model="batchAddObj.skuCode"
          ></el-input>
        </el-col>
        -->
        <el-col :span="4">
          <el-input-number
            size="mini"
            controls-position="right"
            placeholder="市场价(元)"
            v-model="batchAddObj.marketPrice"
            :precision="2"
            :step="0.01"
            :min="0.01"
            :max="99999999"
            :disabled="skuTableType"
            class="input-number"
          ></el-input-number>
        </el-col>
        <el-col :span="4">
          <el-input-number
            size="mini"
            controls-position="right"
            placeholder="销售价-Android(元)"
            v-model="batchAddObj.androidSalesPrice"
            :precision="2"
            :step="0.01"
            :min="0.01"
            :max="99999999"
            :disabled="skuTableType"
            class="input-number"
          ></el-input-number>
        </el-col>
        <el-col :span="4">
          <el-input-number
            size="mini"
            controls-position="right"
            placeholder="销售价-IOS(元)"
            v-model="batchAddObj.iosSalesPrice"
            :precision="2"
            :step="0.01"
            :min="0.01"
            :max="99999999"
            :disabled="skuTableType"
            class="input-number"
          ></el-input-number>
        </el-col>
        <el-col :span="4">
          <el-input-number
            size="mini"
            controls-position="right"
            placeholder="销售价-TOB(元)"
            v-model="batchAddObj.tobSalesPrice"
            :precision="2"
            :step="0.01"
            :min="0.01"
            :max="99999999"
            :disabled="skuTableType"
            class="input-number"
          ></el-input-number>
        </el-col>
        <el-col :span="4">
          <el-input-number
            size="mini"
            controls-position="right"
            placeholder="库存"
            v-model="batchAddObj.stock"
            :precision="0"
            :step="1"
            :min="1"
            :max="99999999"
            :disabled="skuTableType"
            class="input-number"
          ></el-input-number>
        </el-col>
        <el-col :span="3">
          <span style="visibility: hidden">-</span>
        </el-col>
        <el-col :span="4">
          <el-input-number
            size="mini"
            controls-position="right"
            placeholder="最大购买数"
            v-model="batchAddObj.maxPurchaseNum"
            :precision="0"
            :step="1"
            :min="1"
            :max="99"
            :disabled="skuTableType"
            class="input-number"
          ></el-input-number>
        </el-col>
        
      </el-row>
      <el-row :gutter="10" v-if="skuData.length > 0">
        <el-col :span="3">
          <span style="visibility: hidden">-</span>
        </el-col>

        <el-col :span="3">
          <el-button type="primary" size="mini" :disabled="skuTableType" @click="batchAdd"
            >确认</el-button
          >
        </el-col>
      </el-row>
      <br />
      <el-table :data="skuData" size="mini" fit highlight-current-row border>
        <el-table-column prop="id" label="SKU ID" align="center" width="150">
          <template slot-scope="scope">
            {{ !scope.row.id ? '-' : scope.row.id }}
          </template>
        </el-table-column>
        <el-table-column
          v-for="(item, index) in specData"
          :key="item.id"
          :prop="item.id"
          :label="item.value"
          align="center"
        >
          <template slot-scope="scope">{{
            scope.row.specs[index].specValueName
          }}</template>
        </el-table-column>
        <el-table-column prop="picUrl" label="图片" align="center" width="120">
          <template slot-scope="scope">
            <image-selector
              :dialogVisible.sync="showImageSelector"
              @confirm="onImageSelectorConfirm"
            ></image-selector>

            <img
              v-if="scope.row.picUrl"
              :src="scope.row.picUrl"
              alt
              style="width: 100px; height: 100px; cursor: pointer"
              @click="addImg(scope.row)"
              :disabled="skuTableType"
            />
            <el-button
              v-else
              icon="el-icon-plus"
              :disabled="skuTableType"
              @click="addImg(scope.row)"
            ></el-button>
          </template>
        </el-table-column>
        <!--
        <el-table-column
          prop="skuCode"
          label="sku编码"
          align="center"
          width="150"
        >
          <template slot-scope="scope">
            <el-input
              size="mini"
              clearable
              v-model="scope.row['skuCode']"
              :disabled="!scope.row['enable']"
            ></el-input>
          </template>
        </el-table-column>
        -->
        <el-table-column prop="marketPrice" align="center" width="180">
          <template slot="header" slot-scope="scope">
            市场价(元)
            <span style="color: red; margin-left: 5px; font-size: large">*</span>
          </template>
          <template slot-scope="scope">
            <el-input-number
              size="mini"
              controls-position="right"
              v-model="scope.row['marketPrice']"
              :precision="2"
              :step="0.01"
              :min="0.01"
              :max="99999999"
              :disabled="!scope.row['enable']||skuTableType"
            ></el-input-number>
          </template>
        </el-table-column>


        <el-table-column prop="androidSalesPrice" align="center" width="180">
          <template slot="header" slot-scope="scope">
            销售价-Android(元)
            <span style="color: red; margin-left: 5px; font-size: large">*</span>
          </template>
          <template slot-scope="scope">
            <el-input-number
              size="mini"
              controls-position="right"
              v-model="scope.row['androidSalesPrice']"
              :precision="2"
              :step="0.01"
              :min="0.01"
              :max="99999999"
              :disabled="!scope.row['enable']||skuTableType"
            ></el-input-number>
          </template>
        </el-table-column>

        <el-table-column prop="iosSalesPrice" align="center" width="180">
          <template slot="header" slot-scope="scope">
            销售价-IOS(元)
            <span style="color: red; margin-left: 5px; font-size: large">*</span>
          </template>
          <template slot-scope="scope">
            <el-input-number
              size="mini"
              controls-position="right"
              v-model="scope.row['iosSalesPrice']"
              :precision="2"
              :step="0.01"
              :min="0.01"
              :max="99999999"
              :disabled="!scope.row['enable']||skuTableType"
            ></el-input-number>
          </template>
        </el-table-column>

        <el-table-column prop="tobSalesPrice" align="center" width="180">
          <template slot="header" slot-scope="scope">
            销售价-TOB(元)
            <span style="color: red; margin-left: 5px; font-size: large">*</span>
          </template>
          <template slot-scope="scope">
            <el-input-number
              size="mini"
              controls-position="right"
              v-model="scope.row['tobSalesPrice']"
              :precision="2"
              :step="0.01"
              :min="0.01"
              :max="99999999"
              :disabled="!scope.row['enable']||skuTableType"
            ></el-input-number>
          </template>
        </el-table-column>

        <el-table-column prop="stock" label="库存" align="center" width="180">
          <template slot="header" slot-scope="scope">
            库存
            <span style="color: red; margin-left: 5px; font-size: large">*</span>
          </template>
          <template slot-scope="scope">
            <el-input-number
              size="mini"
              controls-position="right"
              v-model="scope.row['stock']"
              :precision="0"
              :step="1"
              :min="0"
              :max="99999999"
              :disabled="!scope.row['enable']||skuTableType"
            ></el-input-number>
          </template>
        </el-table-column>

        <el-table-column
          prop="maxPurchaseNum"
          label="最大购买数"
          align="center"
          width="180"
        >
          <template slot="header" slot-scope="scope">
            最大购买数
            <span style="color: red; margin-left: 5px; font-size: large">*</span>
          </template>
          <template slot-scope="scope">
            <el-input-number
              size="mini"
              controls-position="right"
              v-model="scope.row['maxPurchaseNum']"
              :precision="0"
              :step="1"
              :min="1"
              :max="99"
              :disabled="skuTableType"
            ></el-input-number>
          </template>
        </el-table-column>

        <el-table-column prop="serviceTime" label="服务" align="center" width="180">
          <template slot="header" slot-scope="scope">
            服务周期(月)
            <span style="color: red; margin-left: 5px; font-size: large">*</span>
          </template>
          <template slot-scope="scope">
            <el-input-number
              size="mini"
              controls-position="right"
              v-model="scope.row['serviceTime']"
              :precision="0"
              :step="1"
              :min="1"
              :max="9999"
              :disabled="skuTableType"
            ></el-input-number>
          </template>
        </el-table-column>

        <el-table-column prop="sort" label="排序字段" align="center" width="180">
          <template slot="header" slot-scope="scope">
            排序字段
            <span style="color: red; margin-left: 5px; font-size: large">*</span>
          </template>
          <template slot-scope="scope">
            <el-input-number
              size="mini"
              controls-position="right"
              v-model="scope.row['sort']"
              :precision="0"
              :step="1"
              :min="0"
              :max="9999"
              :disabled="skuTableType"
            ></el-input-number>
          </template>
        </el-table-column>

        <el-table-column label="是否启用" align="center" width="110">
          <template slot-scope="scope">
            <el-switch
              active-value="1"
              inactive-value="0"
              v-model="scope.row['enable']"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :disabled="skuTableType"
            ></el-switch>
          </template>
        </el-table-column>
      </el-table>
      {{ skuData.length }}条
    </div>
  </basic-container>
</template>

<script>
import ImageSelector from "@/components/ImageSelector";
import { flatten } from "@/utils/sku";
import { diffArary } from "@/utils/index";

export default {
  components: {
    ImageSelector,
  },
  props: {
    form: {
      type: Object,
    },
    specData: {
      type: Array,
      default() {
        return [];
      },
    },
    goodsSku: {
      type: Array,
    },
    skuTableType: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    skusList() {
      let skusList = flatten(this.specData).map((item) => ({
        specs: item.specs,
        specIds: item.specs.reduce(
          (total, prev, index) =>
            `${total}${prev.specId}-${prev.specValueId}${
              index === item.specs.length - 1 ? "" : "_"
            }`,
          ""
        ),
      }));
      let skusList2 = this.goodsSku.map((item) => ({
        ...item,
        specIds: item.specs.reduce(
          (total, prev, index) =>
            `${total}${prev.specId}-${prev.specValueId}${
              index === item.specs.length - 1 ? "" : "_"
            }`,
          ""
        ),
      }));
      let that = this;
      skusList.forEach(function (item, index) {
        skusList2.forEach(function (item2, index2) {
          let itemList = item.specIds.split("_");
          let item2List = item2.specIds.split("_");
          let is = true;
          itemList.forEach(function (item3, index2) {
            if (!item2List.find((c) => c == item3)) {
              is = false;
            }
          });
          if (is) {
            that.$set(item, "id", item2.id ? item2.id : undefined);
            that.$set(item, "picUrl", item2.picUrl ? item2.picUrl : "");
            that.$set(item, "picUrls", item2.picUrl ? [item2.picUrl] : []);
            that.$set(item, "skuCode", item2.skuCode ? item2.skuCode : undefined);
            that.$set(item, "salesPrice", item2.salesPrice);
            that.$set(item, "marketPrice", item2.marketPrice);
            that.$set(item, "costPrice", item2.costPrice);
            that.$set(item, "stock", item2.stock);
            that.$set(item, "maxPurchaseNum", item2.maxPurchaseNum);
            that.$set(item, "enable", item2.enable);
            that.$set(item, "androidSalesPrice", item2.androidSalesPrice);
            that.$set(item, "iosSalesPrice", item2.iosSalesPrice);
            that.$set(item, "tobSalesPrice", item2.tobSalesPrice);
            that.$set(item, "serviceTime", item2.serviceTime);
            that.$set(item, "sort", item2.sort);
          }
        });
      });
      return skusList;
    },
  },
  watch: {
    form(val) {},
    skuData: {
      deep: true,
      immediate: true,
      handler(newSkus, oldSkus) {
        console.log(
          "🚀 ~ file: sku-table.vue ~ line 313 ~ handler ~ newSkus",
          newSkus
        );
        this.$emit("getGoodsSku", newSkus);
      },
    },
    skusList: {
      deep: true,
      immediate: true,
      handler(newSkus, oldSkus) {
        if (!newSkus || !newSkus.length) return (this.skuData = []);
        if (!oldSkus || !oldSkus.length) {
          return (this.skuData = newSkus.map((item) => ({
            ...item,
            // 初始化属性
            id: item.id ? item.id : undefined,
            picUrl: item.picUrl ? item.picUrl : "",
            picUrls: item.picUrls ? item.picUrls : [],
            skuCode: item.skuCode ? item.skuCode : undefined,
            salesPrice: item.salesPrice ? item.salesPrice : 0.01,
            marketPrice: item.marketPrice ? item.marketPrice : 0.01,
            costPrice: item.costPrice ? item.costPrice : 0.01,
            stock: item.stock ? item.stock : 0,
            enable: item.enable ? item.enable : "1",
            maxPurchaseNum: item.maxPurchaseNum ? item.maxPurchaseNum : 1,
            androidSalesPrice: item.androidSalesPrice ? item.androidSalesPrice : 0.01,
            iosSalesPrice: item.iosSalesPrice ? item.iosSalesPrice : 0.01,
            tobSalesPrice: item.tobSalesPrice ? item.tobSalesPrice : 0.01,
            serviceTime: item.serviceTime ? item.serviceTime : 1,
            sort: item.sort ? item.sort : 0,
          })));
        }
        // 当规格名的数量发生了变化
        if (newSkus[0].specs.length !== oldSkus[0].specs.length) {
          return (this.skuData = newSkus.map((item) => ({
            ...item,
            // 初始化属性
            id: undefined,
            picUrl: "",
            picUrls: [],
            skuCode: undefined,
            salesPrice: 0.01,
            marketPrice: 0.01,
            costPrice: 0.01,
            stock: 0,
            enable: "1",
            maxPurchaseNum: 1,
            androidSalesPrice: 0.01,
            iosSalesPrice: 0.01,
            tobSalesPrice: 0.01,
            serviceTime: 1,
            sort: 0
          })));
        }
        if (newSkus.length === oldSkus.length) {
          // 当规格名和规格值数量未发生变化，更新 specs 即可
          return (this.skuData = newSkus.map((item, index) => ({
            ...this.skuData[index],
            ...item,
          })));
        }

        const diffIds = this.diffIds(newSkus, oldSkus);
        if (newSkus.length > oldSkus.length) {
          // 当添加了规格值
          let data = [];
          newSkus.forEach((item) => {
            const sku = this.skuData.find(
              (_item) => _item.specIds === item.specIds
            );
            if (sku) {
              data.push(sku);
            } else {
              data.push({
                ...item,
                id: undefined,
                picUrl: "",
                picUrls: [],
                skuCode: undefined,
                salesPrice: 0.01,
                marketPrice: 0.01,
                costPrice: 0.01,
                stock: 0,
                enable: "1",
                maxPurchaseNum: 1,
                maxPurchaseNum: 1,
                androidSalesPrice: 0.01,
                iosSalesPrice: 0.01,
                tobSalesPrice: 0.01,
                serviceTime: 1,
                sort: 0
              });
            }
          });
          this.skuData = data;
        } else {
          // 当删除了规格值
          this.skuData = this.skuData.filter(
            (_item) => !diffIds.includes(_item.specIds)
          );
        }
      },
    },
  },
  data() {
    return {
      batchAddObj: {},
      skuData: [],
      coefficient: {
        purchase_coefficient: 0,
        guide_coefficient: 0,
      },
      showImageSelector: false,
      addingImgRow: null, // 正在添加图片的那一行table row对象
    };
  },
  methods: {
    batchAdd() {
      let that = this;
      this.skuData.forEach(function (val, index) {
        if (val.enable == "1") {
          if (that.batchAddObj.skuCode) {
            that.$set(val, "skuCode", that.batchAddObj.skuCode);
          }
          if (that.batchAddObj.salesPrice >= 0) {
            that.$set(val, "salesPrice", that.batchAddObj.salesPrice);
          }
          if (that.batchAddObj.marketPrice >= 0) {
            that.$set(val, "marketPrice", that.batchAddObj.marketPrice);
          }
          if (that.batchAddObj.costPrice >= 0) {
            that.$set(val, "costPrice", that.batchAddObj.costPrice);
          }
          if (that.batchAddObj.stock >= 0) {
            that.$set(val, "stock", that.batchAddObj.stock);
          }
          if (that.batchAddObj.stock >= 0) {
            that.$set(val, "stock", that.batchAddObj.stock);
          }
          if (that.batchAddObj.maxPurchaseNum >= 0) {
            that.$set(val, "maxPurchaseNum", that.batchAddObj.maxPurchaseNum);
          }
          if (that.batchAddObj.androidSalesPrice >= 0) {
            that.$set(val, "androidSalesPrice", that.batchAddObj.androidSalesPrice);
          }
          if (that.batchAddObj.iosSalesPrice >= 0) {
            that.$set(val, "iosSalesPrice", that.batchAddObj.iosSalesPrice);
          }
          if (that.batchAddObj.tobSalesPrice >= 0) {
            that.$set(val, "tobSalesPrice", that.batchAddObj.tobSalesPrice);
          }
          if (that.batchAddObj.serviceTime >= 0) {
            that.$set(val, "serviceTime", that.batchAddObj.serviceTime);
          }
          if (that.batchAddObj.sort >= 0) {
            that.$set(val, "sort", that.batchAddObj.sort);
          }
        }
      });
    },
    diffIds(skusList1, skusList2) {
      // 两个数据的 id 进行相差
      skusList1 = skusList1.map((item) => item.specIds);
      skusList2 = skusList2.map((item) => item.specIds);
      return diffArary(skusList1, skusList2);
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        if (rowIndex % 2 === 0) {
          return {
            rowspan: 2,
            colspan: 1,
          };
        } else {
          return {
            rowspan: 0,
            colspan: 0,
          };
        }
      }
    },
    /**
     * 添加图片
     */
    addImg(row) {
      debugger
      if(this.skuTableType==false){
         this.showImageSelector = true;
      }   
      this.addingImgRow = row;
    },
    /**
     * 选中图片确认
     */
    onImageSelectorConfirm(selectedItem) {
      // this.addingImgRow.picUrls = [];
      // this.addingImgRow.picUrls.push(selectedItem.url);
      this.addingImgRow.picUrl = selectedItem.url;
    },
  },
};
</script>
<style lang="scss" scoped>
.input-number{
  width:200px;
}
.sku-table .avue-upload__avatar {
  width: 60px;
  height: 60px;
}
.sku-table .avue-upload__icon {
  width: 60px;
  height: 60px;
  line-height: 60px !important;
}
.sku-table .el-upload__tip {
  margin-top: unset;
}
.sku-table .avue-group__item {
  background-color: unset;
}
.sku-table .avue-group__item {
  margin-bottom: unset;
}
.sku-table .el-form-item {
  margin-bottom: unset;
}
.sku-table .el-col {
  margin-bottom: unset;
  line-height: 32px;
}
.sku-table .el-table .el-input-number--mini {
  width: 150px;
}
</style>
